package com.code.family.controller;

import com.code.family.utils.ResultVo;
import com.code.family.config.CustomConfig;
import io.swagger.annotations.Api;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author 上玄
 * since 2024-12-22
 */
@RestController
@RequestMapping("/api/upload")
@Api(tags = "上传文件")
@Slf4j
public class UploadController {
    // 保存上传文件的目录
    private static final String UPLOAD_DIR = "src/main/resources/static/uploads/";
    @Resource
    private CustomConfig customConfig;

    // 实现上传文件功能
    @PostMapping("/file")
    public ResultVo uploadFile(@RequestParam("file") MultipartFile file) {
        log.info("上传文件...");
        // 检查文件是否为空
        if (file.isEmpty()) {
            return ResultVo.error("文件为空");
        }
        // 检查文件扩展名是否合法
        String originalFileName = file.getOriginalFilename();
        if (!originalFileName.endsWith(".jpg") && !originalFileName.endsWith(".png") && !originalFileName.endsWith(".jpeg")) {
            return ResultVo.error("文件扩展名不合法");
        }

        try {
            // 检查上传目录是否存在，不存在则创建
            Path uploadDir = Paths.get(UPLOAD_DIR).toAbsolutePath().normalize();
            if (!uploadDir.toFile().exists()) {
                Files.createDirectories(uploadDir);
            }
            // 创建目标文件路径
            String fileName = originalFileName;
            Path targetPath = Paths.get(UPLOAD_DIR + fileName).toAbsolutePath().normalize();
            // 检查目标文件是否存在，生成UUID重命名文件
            if (targetPath.toFile().exists()) {
                String uuid = java.util.UUID.randomUUID().toString().replaceAll("-", "");
                String extension = fileName.substring(fileName.lastIndexOf('.'));
                String baseName = fileName.substring(0, fileName.lastIndexOf('.'));
                String newFileName = uuid + extension;
                targetPath = Paths.get(UPLOAD_DIR + newFileName).toAbsolutePath().normalize();
                fileName = newFileName; // 更新文件名
            }
            // 将文件保存到目标路径
            Files.copy(file.getInputStream(), targetPath);
            log.info("文件上传成功，路径：{}", targetPath.toString());
            // 构建文件URL
            String fileUrl = customConfig.getFullUploadPath() + fileName;
            log.info("文件URL: {}", fileUrl);

            return ResultVo.success("文件上传成功", fileUrl); // 返回新的文件URL
        } catch (IOException ex) {
            log.error("文件上传失败", ex);
            return ResultVo.error("文件上传失败");
        }
    }
}
